Bubble Sort

Bubble sort is one of the simplest sorting algorihtms to understand, however it is also one of the most inefficient. In the worst case the time complexity is O(n²)


In [8]:
import random

def bubblesort(input_array):
    length = len(input_array)
    for i in range(length):
        for j in range(length - 1):
            if input_array[j] > input_array[j + 1]:
                input_array[j], input_array[j + 1] = input_array[j + 1], input_array[j]
    return input_array
                
bubblesort([random.random() for i in range(10)])


Out[8]:
[0.03504801894079712,
 0.1687530283429841,
 0.24861352535831183,
 0.3274048046031258,
 0.41639752736128643,
 0.43202640650079094,
 0.6789017249849019,
 0.6999805984998514,
 0.8414538519221423,
 0.8827874067516712]